package tech.eyao.hs60x.serviceImpl;

import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import tech.eyao.hs60x.co.LbsCo;
import tech.eyao.hs60x.common.ConstantsKey;
import tech.eyao.hs60x.converts.LbsConvert;
import tech.eyao.hs60x.dao.LbsDao;
import tech.eyao.hs60x.dto.BaseResult;
import tech.eyao.hs60x.model.domain.LbsDO;
import tech.eyao.hs60x.redis.template.LbsCoRedisTemplate;
import tech.eyao.hs60x.service.LbsService;
import tech.eyao.hs60x.utils.DateUtil;

/**
 * lbs 轨迹
 * @author hejian
 * @date 2018年1月9日 下午2:28:57
 */
@Service
public class LbsServiceImpl implements LbsService {
	@Autowired
	private LbsDao lbsDao;
	@Autowired
	private LbsCoRedisTemplate lbsCoRedisTemplate;
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	private static final Logger logger = LoggerFactory.getLogger(LbsServiceImpl.class);

	@Override
	public List<LbsDO> getPageListByWatchId(long accountId, long watchId, long id, Date startDate, Date endDate) {
		if(null == startDate) {
			startDate = DateUtil.getStartTime(new Date());
		}
		if(null == endDate) {
			endDate = DateUtil.getEndTime(new Date());
		}
		return lbsDao.getPageListByWatchId(watchId, id, startDate, endDate);
	}

	@Override
	public boolean insert(long watchId,double longitude, double latitude, int accuracy, int type, String address1, String address2,long  gpsTimesTamp) {
		boolean result = Boolean.TRUE;
		try {
			LbsDO lbsDO = new LbsDO();
			lbsDO.setWatchId(watchId);
			lbsDO.setLatitude(latitude);
			lbsDO.setLongitude(longitude);
			lbsDO.setAccuracy(accuracy);
			lbsDO.setType(type);
			lbsDO.setAddress1(address1);
			lbsDO.setAddress2(address2);
			lbsDO.setGpsTimesTamp(gpsTimesTamp);
			result = lbsDao.insert(lbsDO);
			if(result) {
				LbsCo lbsCo = new LbsCo();
				lbsCo.lastDate = lbsDO.getGmtCreated();
				lbsCo.latitude = latitude;
				lbsCo.longitude = longitude;
				lbsCo.type = type;
				lbsCo.accuracy = accuracy;
				lbsCo.address1 = address1;
				lbsCo.address2 = address2;
				lbsCo.gpsTimesTamp =gpsTimesTamp;
				lbsCoRedisTemplate.opsForValue().set(ConstantsKey.getLastWatchLbsKey(watchId), lbsCo);
			}
		} catch (Exception e) {
			logger.error("[LbsService insert error.]", e);
		}
		
		return result;
	}

	@Override
	public BaseResult getWatchLbs(long watchId) {
		BaseResult baseResult = new BaseResult();
		try {
			LbsCo lbsCo = lbsCoRedisTemplate.opsForValue().get(ConstantsKey.getLastWatchLbsKey(watchId));
			baseResult.data = LbsConvert.convert(lbsCo,stringRedisTemplate.opsForValue().get(ConstantsKey.getWatchElectricitKey(watchId)));
			return baseResult; 
		} catch (Exception e) {
			logger.error("[LbsService getWatchLbs] error.", e);
		}
		return null;
	}
}
